<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI 对话助手</title>
    <style>
        :root {
            --primary-color: #4a90e2;
            --background: #f5f7fb;
            --card-bg: #ffffff;
        }

        body {
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif;
            background: var(--background);
            height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .chat-container {
            flex: 1;
            max-width: 800px;
            margin: 20px auto;
            width: 90%;
            background: var(--card-bg);
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }

        .messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .message {
            max-width: 80%;
            padding: 12px 16px;
            border-radius: 18px;
            line-height: 1.5;
        }

        .user-message {
            align-self: flex-end;
            background: var(--primary-color);
            color: white;
            border-radius: 18px 18px 4px 18px;
        }

        .ai-message {
            align-self: flex-start;
            background: #f1f3f6;
            color: #333;
            border-radius: 18px 18px 18px 4px;
        }

        .input-area {
            padding: 20px;
            background: var(--card-bg);
            border-top: 1px solid #eee;
            display: flex;
            gap: 10px;
        }

        #input {
            flex: 1;
            padding: 12px 16px;
            border: 1px solid #ddd;
            border-radius: 25px;
            font-size: 16px;
            outline: none;
            transition: border-color 0.3s;
        }

        #input:focus {
            border-color: var(--primary-color);
        }

        button {
            padding: 12px 24px;
            background: var(--primary-color);
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            transition: opacity 0.3s;
        }

        button:hover {
            opacity: 0.9;
        }

        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }

        .message pre {
            background: #f8f8f8;
            padding: 15px;
            border-radius: 8px;
            overflow-x: auto;
        }

        .message code {
            font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
            font-size: 14px;
        }

        .message table {
            border-collapse: collapse;
            margin: 1em 0;
        }

        .message th, .message td {
            border: 1px solid #ddd;
            padding: 8px 12px;
        }

        .message blockquote {
            border-left: 4px solid #ddd;
            margin: 1em 0;
            padding-left: 1em;
            color: #666;
        }
    </style>

    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.6.0/build/highlight.min.js"></script>
    <link rel="stylesheet"
          href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.6.0/build/styles/github.min.css">
</head>
<body>
<div class="chat-container">
    <div class="messages" id="messages"></div>
    <div class="input-area">
        <input type="text" id="input" placeholder="输入您的问题...">
        <button onclick="sendMessage()" id="sendBtn">发送</button>
    </div>
</div>

<script>
    const messagesDiv = document.getElementById('messages');
    const input = document.getElementById('input');
    const sendBtn = document.getElementById('sendBtn');

    // 配置Markdown解析器
    marked.setOptions({
        highlight: (code, lang) => {
            const language = hljs.getLanguage(lang) ? lang : 'plaintext';
            return hljs.highlight(code, {language}).value;
        },
        breaks: true,
        sanitize: true // 防止XSS攻击
    });

    function addMessage(content, isUser = true) {
        const div = document.createElement('div');
        div.className = `message ${isUser ? 'user-message' : 'ai-message'}`;

        // 仅AI消息解析Markdown
        if (!isUser) {
            div.innerHTML = marked.parse(content); // 使用Markdown解析
            div.querySelectorAll('pre code').forEach(hljs.highlightElement);
        } else {
            div.textContent = content; // 用户消息保持纯文本
        }

        messagesDiv.appendChild(div);
        scrollToBottom();
    }

    // 发送消息
    async function sendMessage() {
        const prompt = input.value.trim();
        if (!prompt) return;

        sendBtn.disabled = true;
        input.value = '';
        addMessage(prompt, true);

        let heartbeatTimer;
        let isStreaming = true;

        try {
            const response = await fetch(`/sse/chat?prompt=${encodeURIComponent(prompt)}`);
            const reader = response.body.getReader();
            const decoder = new TextDecoder();

            // 新增原始内容缓存
            let aiRawContent = '';
            // 创建AI消息容器
            let aiMessage = document.createElement('div');
            aiMessage.className = 'message ai-message';
            messagesDiv.appendChild(aiMessage);

            // SSE心跳检测
            heartbeatTimer = setInterval(() => {
                console.debug('保持SSE连接活跃');
            }, 55000);

            // 流处理相关变量
            let buffer = '';
            let renderTimer;

            // 流式处理函数
            const processChunk = ({done, value}) => {
                if (done) {
                    if (buffer.length > 0) processRemaining();
                    return;
                }

                buffer += decoder.decode(value, {stream: true});
                processEvents();
                return reader.read().then(processChunk);
            };

            // 事件处理逻辑
            const processEvents = () => {
                const events = buffer.split('\n\n');
                if (events.length === 1) return;

                buffer = events.pop(); // 保留未完成数据
                events.forEach(event => handleEvent(event));
            };

            // 单个事件处理
            const handleEvent = (event) => {
                if (!event.startsWith('data:')) return;

                const rawData = event.slice(5).trim();
                if (rawData === '[DONE]') {
                    console.log('流式传输结束');
                    return;
                }

                try {
                    const data = JSON.parse(rawData);
                    if (data?.choices?.[0]?.delta?.content) {
                        safeAppendContent(data.choices[0].delta.content);
                    }
                } catch (e) {
                    console.warn('解析异常:', e);
                }
            };

            // 安全追加内容（带节流）
            const safeAppendContent = (content) => {
                aiRawContent += content;
                if (!renderTimer) {
                    renderTimer = setTimeout(() => {
                        // 使用防抖渲染Markdown
                        aiMessage.innerHTML = marked.parse(aiRawContent);
                        aiMessage.querySelectorAll('pre code').forEach(hljs.highlightElement);
                        scrollToBottom();
                        renderTimer = null;
                    }, 500);
                }
            };

            // 启动流处理
            reader.read().then(processChunk);

        } catch (error) {
            console.error('请求失败:', error);
            if (isStreaming) {
                addMessage('连接异常，请重试', false);
            }
        } finally {
            clearInterval(heartbeatTimer);
            sendBtn.disabled = false;
            isStreaming = false;
        }
    }

    // 剩余数据处理（最后调用）
    function processRemaining() {
        if (buffer.length > 0) {
            handleEvent(buffer);
            buffer = '';
        }
    }

    // 自动滚动优化
    function scrollToBottom() {
        messagesDiv.scrollTop = messagesDiv.scrollHeight;
    }

    // 回车发送
    input.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') sendMessage();
    });
</script>
</body>
</html>
